<template>
  <view class="container">
    <!-- 发货 -->
    <uni-forms
      ref="formRef"
      :model="formData"
      label-position="top"
      label-width="75vw"
      :rules="rules">
      <uni-forms-item name="isTransportCode" required label="请选择有无交委电子运单">
        <!-- <view class="title"></view> -->
        <uni-data-checkbox
          v-model="formData.isTransportCode"
          :localdata="optionItems"
          @change="onChangeInoutType">
        </uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="transportCode" label="请扫描或输入电子运单" v-if="formData.isTransportCode == 1" required>
        <!-- <view class="title"></view> -->
        <uni-easyinput suffixIcon="scan" type="text" @change="onChangeTransportCode" v-model="formData.transportCode" placeholder="请输入" maxlength="24" @iconClick="onClickScanCode" />
      </uni-forms-item>
      <uni-forms-item name="carNo" :label="`请${carList.length > 0 ? '选择' : '输入'}承运车辆车牌号`" required>
        <!-- <view class="title"></view> -->
        <uni-data-select
          v-model="formData.carNo"
          :localdata="carList"
          @change="onChangeCarNo"
          v-if="carList.length > 0"
          style="background:#fff"
        ></uni-data-select>

        <!--  v-if="formData.isTransportCode == 1" -->
        <uni-easyinput @change="onChangeCarNo" v-if="carList.length == 0 || formData.isTransportCode == 2" type="text" v-model="formData.carNo" placeholder="请输入" />
      </uni-forms-item>
      <uni-forms-item name="isToOuter" label="是否发往外省市" required>
        <!-- <view class="title"></view> -->
        <uni-data-checkbox
          v-model="formData.isToOuter"
          :localdata="optionItemsIsToOuter">
        </uni-data-checkbox>
      </uni-forms-item>
      
      <view>
        <!-- {{carList1}} -->
        <view class="tips">发货前: 确认发货数量</view>
        <view class="list" v-if="productInfo.length > 0">
          <view class="mtitle">
            <h3>发货单货品</h3>
            <!-- <a href="javascript:;" class="del">删除全部</a> -->
          </view>
          <view class="bd">
            <!-- { current: currentIndex === index } -->
            <ul v-for="(item, index) in productInfo" :class="{ current: selectedItems.includes(item) }" @click.stop="fClickProductInfo(item, index)" :key="index">
              <uni-icons class="checkbox" v-if="selectedItems.includes(item)" type="checkbox-filled" color="green" :size="26"></uni-icons>
              <li>
                <span>追溯登记号：</span>
                <span>{{ item.traceUrlUnicode }}</span>
                <!-- <span class="icon">
                  <uni-icons type="trash-filled" size="20"></uni-icons>
                </span> -->
              </li>
              <li>
                <span>发货企业：</span>
                <span>
                  <uni-data-select
                    v-model="item.enterpriseId"
                    :localdata="enterpriseList"
                    style="width:425upx;"
                    :clear="false"
                    @change="onChangeEnterprise"
                   ></uni-data-select>
                </span>
              </li>
              <li>
                <span>货品名称：</span>
                <span>{{ item.merchandiseName }}</span>
              </li>
              <li class="amount">
                <span>发货数量：</span>
                <!-- <span>{{ item.amount }}kg</span> -->
                <span style="display: flex;">
                  <uni-number-box style="width:200upx;" :min="0" :max="1000000" v-model="item.amount" /> &nbsp;&nbsp;kg
                </span>
              </li>
              <!-- <li>
                <span>规格：</span>
                <span>{{ item.unit }}</span>
              </li> -->
              <li>
                <span>追溯批次号：</span>
                <span>{{ item.traceBatchNo }}</span>
              </li>
              <li>
                <span>收货企业：</span>
                <span>
                  <!-- {{ item.receiveEnterpriseName }} -->
                  <!-- <uni-data-select
                    v-model="item.receiveEnterpriseName"
                    :localdata="enterpriseList"
                    style="width:425upx;"
                    :clear="false"
                   ></uni-data-select> -->
                   <uni-easyinput type="text" style="width:425upx;" v-model="item.receiveEnterpriseName" placeholder="请输入" />
                </span>
              </li>
              <li>
                <span>结束时间：</span>
                <span>
                  <uni-datetime-picker
                    v-model="item.loadingEndDate"
                    placeholder="请选择时间"
                    type="datetime"
                    :hide-second="true">
                  </uni-datetime-picker>
                </span>
              </li>
            </ul>
          </view>
        </view>
      </view>
    </uni-forms>
    
    <div class="ft">
      <button type="primary" @click="handleSubmit">发货</button>
    </div>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { apis as APIS } from "@/api/yiqiyipin.js";
import { router } from "@/router/index.js";

const formData = ref({
  carNo: '',
  transportCode: '',
  isToOuter: '',  
  isTransportCode: 1,
  receiveEnterpriseName: '',
  enterpriseName: ''
});

const rules = ref({
  isTransportCode: {
    rules: [{ required: true, errorMessage: "请选择有无交委电子运单" }],
  },
  transportCode: {
    rules: [{ required: true, errorMessage: "请扫描或输入电子运单" }],
  },
  carNo: {
    rules: [{ required: true, errorMessage: "请输入承运车辆车牌号" }],
  },
  isToOuter: {
    rules: [{ required: true, errorMessage: "是否发往外省市" }]
  }
});

const optionItems = [
  {
    value: 1,
    text: "有交委电子运单",
  },
  {
    value: 2,
    text: "无交委电子运单",
  }
]

const optionItemsIsToOuter = [
  {
    value: 1,
    text: "是",
  },
  {
    value: 0,
    text: "否",
  }
]

const carList = ref([])

const onChangeInoutType = () => {
  carList.value = []
  business.value = ''
  formData.value.carNo = ''
  formData.value.transportCode = ''
}

// 选择货单
const info = {}
const unloadIds = ref([])
const currentIndex = ref(null)
const selectedItems = ref([])
const fClickProductInfo = (item, index) => {
  currentIndex.value = index
  info.value = item

  // 检查已选中项数组中是否包含当前点击项
  const selectedIndex = selectedItems.value.indexOf(item);
  if (selectedIndex === -1) {
    // 如果当前项未被选中，则把点击项添加到数组中
    selectedItems.value.push(item);
	unloadIds.value.push(item.unloadId);
    // businessVo
  } else {
    // 如果当前项已被选中，则从已选中项数组中移除
    selectedItems.value.splice(selectedIndex, 1);
	unloadIds.value.splice(selectedIndex, 1);
  }
  
  console.log('unloadIds', unloadIds.value)
  console.log('selectedItems', selectedItems.value)

  // formData.value = selectedItems.value
}

// 输入电子运单号
const onChangeTransportCode = (e) => {
  if(e){
    APIS.carNumList({  transportCode: formData.value.transportCode  }).then((res) => {
      if(res.code === 200){
        // formData.value = res.data
        let { carNo, transportCode, isToOuter, receiveEnterpriseName } = res.data
        formData.value = {
          ...formData.value,
          carNo, transportCode, isToOuter, receiveEnterpriseName
        }
        onChangeCarNo(res.data.carNo)
      }
    });
  }
}

// 根据加密车牌，查询匹配车牌号
const onClickScanCode = (e) => {
  // 扫码出来的内容，车牌号传给接口
  // let str = '02$01$310002032324082200216865$沪FF**63,黄色$王磊,320826******143430,陈太露,321323******243337$mAp4VAYDZKA/j5uMBioanmG4RTBnZbluq+wZmDeGm8iS85i2F70J6JVMy57BeJa4dHW2cbFnrreUDr3U9nFLkA=='

  // formData.value.transportCode = str.split('$')[2]
  // let carNo = str.split('$')[3].split(',')[0]

  // // 根据加密车牌，查询匹配车牌号
  // APIS.carNumList({  transportCode: formData.value.transportCode  }).then((res) => {
  //   if(res.code === 200){
  //     formData.value = res.data
  //   }
  // });
  
  uni.scanCode({
    onlyFromCamera: false, // 是否只从相机扫码，不从相册选择图片
    scanType: ['qrCode'], // 扫描的类型
    success: function (res) {
      console.log('扫描结果：', res.result);
      console.log('扫描条码类型：', res.scanType);
      // console.log('字符集：', res.charSet);
      // console.log('路径：', res.path); // 当所扫的码为小程序码时会返回此项
      
      // 扫码出来的内容，车牌号传给接口
      // 02$01$310002032324082200216865$沪FF**63,黄色$王磊,320826******143430,陈太露,321323******243337$mAp4VAYDZKA/j5uMBioanmG4RTBnZbluq+wZmDeGm8iS85i2F70J6JVMy57BeJa4dHW2cbFnrreUDr3U9nFLkA==
      
      // carList1.value = `${res.result}---${res.scanType}`

      if(res.result){
        formData.value.transportCode = res.result.split('$')[2]
        let carNo = res.result.split('$')[3].split(',')[0]

        // 根据加密车牌，查询匹配车牌号
        APIS.carNumList({  transportCode: formData.value.transportCode  }).then((res) => {
          if(res.code === 200){
            let { carNo, transportCode, isToOuter, receiveEnterpriseName } = res.data
            formData.value = {
              ...formData.value,
              carNo, transportCode, isToOuter, receiveEnterpriseName
            }
            onChangeCarNo(res.data.carNo);
          }
        });
      }
    },
    fail: function (err) {
      console.error('扫码失败：', err);
      uni.showToast({
        title: `扫码失败：${err}`,
      });
    },
    complete: function () {
      console.log('扫码操作完成');
    }
  });
}

// 收货企业
const enterpriseList = ref([])
const fGetEnterpriseList = (e) => {
  APIS.enterpriseList().then((res) => {
    if(res.code === 200){
      res.data.map(item => {
        enterpriseList.value.push({
          enterprise: {
            id: item.id,
            name: item.enterpriseName
          },
          value: item.id,
          text: item.enterpriseName
        })
      })
    }
  });
}
fGetEnterpriseList()

// 根据车牌号查询货品信息   沪FF10163
const business = ref()
const productInfo = ref([])  // 货品信息
const onChangeCarNo = (e) => {
  if(e){
    business.value = ''
    APIS.sendBusinessInfo({ carNo: e }).then((res) => {
      if(res.code === 200){
        // business.value = res.data.business
        productInfo.value = []
        res.data.map(item => {
          productInfo.value.push({
            ...item.businessVo
          })
        })

        console.log(productInfo.value)
      }
    });
  }
}

const onChangeEnterprise = (e) => {
}

const formRef = ref();
const handleSubmit = (data) => {
  formRef.value.validate().then((res) => {
    let data = {
      // selectedItems.value
      // ...formData.value,
      // ...info.value.businessVo,
      // transportCode: formData.value.transportCode

    }

    let arr = []
    selectedItems.value.map(item => {
      arr.push({
        ...formData.value,
        ...item,
        transportCode: formData.value.transportCode
      })
    })

    delete data.enterpriseName
    delete data.receiveEnterpriseId
    APIS.sendBusinessAdd(arr).then((res) => {
      if(res.code === 200){
        uni.showModal({
          title: "提示",
          content: `发货完成，是否打印出库单？`,
          success: function (res) {
            if (res.confirm) {
			  let unloadIds_ = unloadIds.value.join(",");
			  // console.log(unloadIds_);
			  
			  APIS.print(unloadIds_).then((res) => {
			  	if(res.code === 200) {
			  	}
			  });
            }
          }
        });

        // setTimeout(() => {
        //   router.toPage({
        //     path: "/pages/home/index"
        //   });
        // }, 2000);
      }
    });
  })
  .catch((err) => {
    console.log("表单错误信息", err);
  });
}

onMounted(() => {});
</script>

<style lang="scss" scoped>
.container {
  padding: 20upx;
  background: #fff;

  .title{
    font-weight: 500;
    font-size: 30upx;
    padding-bottom: 10upx;
  }

  .tips{
    color: #000;
    font-size: 24upx;
    padding-bottom: 8upx;
  }
  .list{
    background: #fff;
    border: 1upx solid #e1e1e1;
    border-radius: 10upx;
    margin-top: 30upx;

    .mtitle{
      padding: 20upx 30upx;
      display: flex;
      justify-content: space-between;
      border-bottom: 1upx solid #e1e1e1;

      h3{
        font-size: 28upx;
      }
      .del{
        color: #f00;
        text-decoration: none;
      }
    }

    .bd{
      .checkbox{
        position: absolute;
        top: 10upx;
        right: 10upx;
      }

      .current{
        background-color: #e2f0d9;
      }
    }
    
    ul{
      position: relative;
      padding: 25upx 10upx;
      border-bottom: 2upx solid #e1e1e1;

      li{
        list-style: none;
        color: #666;
        line-height: 42upx;
        display: flex;
        align-items: center;
        margin-bottom: 15upx;

        span{
          font-size: 24upx;
        }

        span:nth-child(1){
          width: 210upx;
          text-align: right;
          display: inline-block;
          padding-right: 10upx;
        }
        span:nth-child(2){
          width: 420upx;
        }
        .icon{
          position: relative;
          top: 3upx;
          left: 10upx;
        }
      }
    }
  }

  .ft{
    width: 100%;
    margin-top: 20upx;
  }
}

:deep .uni-select__input-box{
  overflow: hidden;
}
::v-deep .amount .uni-numbox{
  width: 10rem !important;

  .uni-numbox__value{
    width: 10rem !important;
  }
}

::v-deep .bd .uni-select__input-text{
  font-size: 22upx;
}
</style>
